package io.admin.modules.sys.controller;

import cn.hutool.core.collection.CollectionUtil;
import io.admin.common.annotation.LogOperation;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.utils.ExcelUtils;
import io.admin.common.utils.Result;
import io.admin.common.utils.StringUtils;
import io.admin.common.validator.AssertUtils;
import io.admin.common.validator.ValidatorUtils;
import io.admin.common.validator.group.AddGroup;
import io.admin.common.validator.group.DefaultGroup;
import io.admin.common.validator.group.UpdateGroup;
import io.admin.modules.sys.dto.EquipmentDTO;
import io.admin.modules.sys.dto.FileUrlDTO;
import io.admin.modules.sys.dto.ProjectFindDTO;
import io.admin.modules.sys.entity.EquipmentEntity;
import io.admin.modules.sys.entity.EquipmentEntityPage;
import io.admin.modules.sys.excel.EquipmentExcel;
import io.admin.modules.sys.service.EquipmentService;
import io.admin.modules.sys.service.FileUrlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;


/**
 * 设备表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-06
 */
@RestController
@RequestMapping("sysproject/equipment")
@Api(tags="设备表")
public class EquipmentController {
    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private FileUrlService fileUrlService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<EquipmentDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<EquipmentDTO> page = equipmentService.page(params);
        return new Result<PageData<EquipmentDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<EquipmentDTO> get(@PathVariable("id") Long id){
        EquipmentDTO data = equipmentService.get(id);
        return new Result<EquipmentDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    public Result save(@RequestBody EquipmentDTO dto){
        //效验数据
        Long equipmentId =generateRandomLongId();
        Integer  getRepeatByEquipment =equipmentService.getRepeatByEquipment(dto);
        if(getRepeatByEquipment>0){
            return new Result().error("当前设备名称重复了，请重新修改了在提交");
        }
        //开始
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setId(equipmentId);
        dto.setSource(5);
        Integer sort = equipmentService.getSortEnd(dto);
        sort = null ==sort?0:sort;
        sort = sort+1;
        dto.setSort(sort);
        equipmentService.save(dto);
        if(!StringUtils.isBlank(dto.getImgIds())){
            String[] idArray = dto.getImgIds().split(",");
            for (String id:idArray) {
                FileUrlDTO fileUrlDTO =new FileUrlDTO();
                fileUrlDTO.setId(Long.valueOf(id));
                fileUrlDTO.setKeysId(dto.getId());
                fileUrlService.update(fileUrlDTO);
            }
        }
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    public Result update(@RequestBody EquipmentDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        if(null == dto.getType()){
            EquipmentDTO  getRepeatByEquipment =equipmentService.findEqByParam(dto);
            if(null != getRepeatByEquipment  ){
                if(!getRepeatByEquipment.getId().equals(dto.getId())){
                    return new Result().error("当前设备名称重复了，请重新修改了在提交");
                }
            }
            dto.setSource(5);
            if(null != dto.getSort()){
                Integer sort = equipmentService.getSortEnd(dto);
                sort = null ==sort?0:sort;
                sort = sort+1;
                dto.setSort(sort);
            }
            equipmentService.update(dto);
            if(!StringUtils.isBlank(dto.getImgIds())){
                String[] strArray = dto.getImgIds().split(",");
                for (String str:strArray) {
                    FileUrlDTO fileUrlDTO =new FileUrlDTO();
                    fileUrlDTO.setId(Long.valueOf(str));
                    fileUrlDTO.setKeysId(dto.getId());
                    fileUrlService.update(fileUrlDTO);
                }
            }
            return new Result();
        }else if(dto.getType() ==1){
            Map<String,Object> data = equipmentService.getIdDownByThisSortId(dto);
            if(null != data){
                return new Result().error(String.valueOf(data.get("msg")));
            }
            return new Result();
        }else if(dto.getType() ==2){
            Map<String,Object> data = equipmentService.getIdUpByThisSortId(dto);
            if(null != data){
                return new Result().error(String.valueOf(data.get("msg")));
            }
            return new Result();
        }else{
            return new Result();
        }
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        equipmentService.delete(ids);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<EquipmentDTO> list = equipmentService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "设备表", list, EquipmentExcel.class);
    }

    @RequestMapping("/findEquipmentCount")
    public Result findProSelect(HttpServletRequest request, HttpServletResponse response){
        String projectId =request.getParameter("projectId");
        String lineId=request.getParameter("lineId");
         Integer count =equipmentService.getLineCount(!StringUtils.isBlank(lineId)?Long.valueOf(lineId):null
                                                      ,!StringUtils.isBlank(projectId)?Long.valueOf(projectId):null);
        return new Result<>().ok(count);
    }

    @RequestMapping("/findEqByline")
    public Result findEqByline(@RequestParam Map<String, Object> params){
        return new Result<>().ok(equipmentService.getLineList(params));
    }

    @RequestMapping("/findEquipmentByLineList")
    public Result findEquipmentByLineList(@RequestParam(required = false) String lineId,HttpServletRequest request, HttpServletResponse response){
        String projectId =request.getParameter("projectId");
        if(StringUtils.isBlank(projectId)){
          return   new Result<>().ok("");
        }
        Map<String,Object> map =new HashMap<>();
        map.put("lineId",null!=lineId?lineId:null);
        map.put("projectId",Long.valueOf(projectId));
        List<EquipmentEntityPage> equipmentDTOList =  equipmentService.listByProject(map);
        //开始根据类型统计数据
        List<EquipmentEntityPage> resData = new ArrayList<>();
       if(!CollectionUtil.isEmpty(equipmentDTOList)){
           //开始统计数据
           Set<Long> listEqTypeId =equipmentDTOList.stream().distinct().map(i->i.getEquipmentTypeId()).collect(Collectors.toSet());
           if(!CollectionUtil.isEmpty(listEqTypeId)){
               for (Long id:listEqTypeId){
                   List<EquipmentEntityPage> dataType =equipmentDTOList.stream().filter(i->i.getEquipmentTypeId().equals(id)).collect(Collectors.toList());
                   EquipmentEntityPage equipmentEntityPage = new EquipmentEntityPage();;
                   if(!CollectionUtil.isEmpty(dataType)){
                       equipmentEntityPage =dataType.get(0);
                       equipmentEntityPage.setEquipmentTypeNumber(dataType.size());
                       resData.add(equipmentEntityPage);
                   }
               }
           }
           for (EquipmentEntityPage data:equipmentDTOList){
               data.setLat(data.getLgt());
               data.setLng(data.getDms());
           }
       }
        Map<String,Object> ratData = new HashMap<>();
        ratData.put("equipmentData",equipmentDTOList);
        ratData.put("equipmentCountData",resData);
        return new Result<>().ok(ratData);
    }
    public static long generateRandomLongId() {
        return ThreadLocalRandom.current().nextLong();
    }

}